<template>
  <div class="device-type-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="类型名称">
          <el-input v-model="searchParams.typeName" placeholder="输入设备类型名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchParams.isEnable" placeholder="选择是否启用" clearable style="width: 100px;">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd(null)">
            <el-icon><Plus /></el-icon>新增顶级类型
          </el-button>
          <el-button type="danger" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>

      <!-- 树形表格 -->
        <el-table
          ref="deviceTypeTable"
          :data="tableData"
          style="width: 100%"
          border
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          highlight-current-row
          default-expand-all
        >
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="equipmentCode" label="设备类型编码" width="180"></el-table-column>
        <el-table-column prop="equipmentName" label="设备类型名称" width="220"></el-table-column>
        <el-table-column prop="status" label="是否启用" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="descs" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button size="small" type="success" @click="handleAdd(scope.row)">
              新增子项
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑设备类型' : '添加设备类型'"
        width="500px"
        :close-on-click-modal="false"
        :show-close="true"
        @close="resetForm"
        center
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          label-position="right"
          class="equipment-type-form"
        >
          <el-form-item label="父类型" prop="parentTypeCode" v-if="!isEdit || formData.parentTypeCode">
            <el-select 
              v-model="formData.parentTypeCode" 
              placeholder="请选择父类型"
              clearable
              filterable
              :disabled="isEdit"
              @change="handleParentChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.typeCode"
                :label="item.typeName"
                :value="item.typeCode"
              />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备类型名称" prop="typeName" required>
          <el-input v-model="formData.typeName" placeholder="请输入设备类型名称"></el-input>
        </el-form-item>
        
        <el-form-item label="是否启用" required>
          <el-radio-group v-model="formData.isEnable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
            ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取 消</el-button>
          <el-button type="primary" @click="submitForm" class="confirm-btn">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/api/http'
import { Search, Plus, Delete } from '@element-plus/icons-vue';

// API基础路径
const baseApiUrl = '/api/EquipmentType';

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref([]);
  
  // 选中行IDs
  const selectedIds = ref([]);

// 搜索参数
const searchParams = reactive({
    typeName: '',
    isEnable: '',
});

// 表单对话框
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

// 表格引用
const deviceTypeTable = ref(null);

// 表单数据
const formData = reactive({
    typeCode: '',
    typeName: '',
    isEnable: 1,
    remark: '',
    parentTypeCode: '',
    parentTypeName: ''
});

// 父类型选项
const parentOptions = ref([]);

// 表单规则
const formRules = reactive({
  typeName: [
    { required: true, message: '请输入设备类型名称', trigger: 'blur' }
  ],
  isEnable: [
    { required: true, message: '请选择是否启用', trigger: 'change' }
  ]
});

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const typeName = searchParams.typeName || '';
    const status = searchParams.isEnable !== '' ? searchParams.isEnable : '';

    // API调用 - 使用GET请求获取设备类型列表
      const url = `/api/EquipmentType/GetEquipmentTypes?typeName=${encodeURIComponent(typeName)}&status=${status}`;
    const response = await http.get(url);
    console.log('API响应数据:', response);

    if (response && response.status) {
        // 根据控制台输出调整数据处理
      // 处理数据成树形结构
      tableData.value = buildTree(response.data || []);
    } else {
      ElMessage.error(response?.message || '获取数据失败');
      tableData.value = [];
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 构建树形结构
const buildTree = (flatData) => {
  console.log('构建树形结构，原始数据:', flatData);
  if (!Array.isArray(flatData) || flatData.length === 0) {
    return [];
  }

  // 递归处理节点及其子节点
  const processNode = (node) => {
    if (!node) return null;

    // 转换字段名以匹配表格组件需要的字段
    const transformedNode = {
      id: node.id,
      equipmentCode: node.equipmentCode,
      equipmentName: node.equipmentName,
      status: node.status,
      descs: node.descs,
      parentCode: node.parentCode,
      typeCode: node.equipmentCode // 兼容旧代码
    };

    // 递归处理children
    if (node.children && Array.isArray(node.children) && node.children.length > 0) {
      transformedNode.children = node.children.map(child => processNode(child));
    }

    return transformedNode;
  };

  // 处理顶层数据
  const result = flatData.map(item => processNode(item));

  console.log('处理后的树形结构:', result);
  return result;
};

// 搜索
const handleSearch = () => {
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchParams.typeName = '';
  searchParams.isEnable = '';
  fetchData();
};
  
  // 表格选择变化
  const handleSelectionChange = (rows) => {
    selectedIds.value = rows.map(row => row.id || row.equipmentCode).filter(Boolean);
    console.log('选中ID数组:', selectedIds.value);
  };

// 新增
const handleAdd = (parentRow) => {
  isEdit.value = false;
  resetForm();
    loadParentOptions();
  
  // 生成唯一的类型编码
  formData.typeCode = `T${Date.now().toString().substr(-8)}`;
  
  if (parentRow) {
      formData.parentTypeCode = parentRow.id || parentRow.equipmentCode;
    formData.parentTypeName = parentRow.equipmentName;
  }
  
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  isEdit.value = true;
  
  // 映射API返回的字段到表单字段
  formData.typeCode = row.equipmentCode;
  formData.typeName = row.equipmentName;
  formData.isEnable = row.status;
  formData.remark = row.descs || '';
  formData.parentTypeCode = row.parentCode || '';
  
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  Object.assign(formData, {
    typeCode: '',
    typeName: '',
    isEnable: 1,
    remark: '',
    parentTypeCode: '',
    parentTypeName: ''
  });
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    loading.value = true;
    
      // 准备提交的数据
    const submitData = {
      equipmentCode: formData.typeCode,
      equipmentName: formData.typeName,
      status: formData.isEnable,
      descs: formData.remark || '',
      parentCode: formData.parentTypeCode || ''
    };
    
    let response;
    
    if (isEdit.value) {
      // 更新设备类型
      response = await http.post(`/api/EquipmentType/UpdEquipmentType`, submitData);
    } else {
      // 添加设备类型
      response = await http.post(`/api/EquipmentType/AddEquipmentType`, submitData);
    }
    
    if (response && response.status) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response?.message || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('操作失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除此设备类型吗？该操作将删除所有子类型', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 删除单个设备类型
      const response = await http.post(`${baseApiUrl}/DelEquipmentTypes?ids=${id}`);
    
    if (response && response.status) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};
  
  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedIds.value.length === 0) {
      ElMessage.warning('请至少选择一条记录');
      return;
    }
    
    try {
      await ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录？该操作将删除所有子类型`, '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      });
      
      loading.value = true;
      
      // 批量删除设备类型
      const ids = selectedIds.value.join(',');
      const response = await http.post(`/api/EquipmentType/DelEquipmentTypes?ids=${ids}`);
      
      if (response && response.status) {
        ElMessage.success('批量删除成功');
        fetchData();
      } else {
        ElMessage.error(response?.message || '批量删除失败');
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除出错:', error);
        ElMessage.error('批量删除失败，请稍后再试');
      }
    } finally {
      loading.value = false;
    }
  };
  
  // 处理父类型变化
  const handleParentChange = (value) => {
    if (value) {
      const parent = parentOptions.value.find(item => item.typeCode === value);
      if (parent) {
        formData.parentTypeName = parent.typeName;
      }
    } else {
      formData.parentTypeName = '';
    }
  };
  
  // 加载父类型选项
  const loadParentOptions = async () => {
    try {
      // API调用获取所有可用作父类型的选项
      const url = `/api/EquipmentType/GetEquipmentTypes?status=1`;
      const response = await http.get(url);
      
      if (response && response.status) {
        // 处理返回数据，确保字段名称一致
        const processOptions = (items) => {
          if (!items || !Array.isArray(items)) return [];
          
          let options = [];
          
          items.forEach(item => {
            options.push({
              typeCode: item.id || item.equipmentCode,
              typeName: item.equipmentName
            });
            
            if (item.children && Array.isArray(item.children) && item.children.length > 0) {
              options = options.concat(processOptions(item.children));
            }
          });
          
          return options;
        };
        
        parentOptions.value = processOptions(response.data || []);
    } else {
      parentOptions.value = [];
    }
  } catch (error) {
    console.error('获取父类型选项出错:', error);
    parentOptions.value = [];
  }
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.device-type-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-table .el-table__row--level-1) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row--level-2) {
  background-color: #ebeef5;
}

.equipment-type-form :deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

.equipment-type-form :deep(.el-form-item__label::before) {
  color: #f56c6c;
}

.cancel-btn {
  width: 80px;
}

.confirm-btn {
  width: 80px;
  background-color: #409eff;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  text-align: center;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}

:deep(.el-select .el-input__inner) {
  height: 32px;
}

:deep(.el-radio) {
  margin-right: 30px;
}
</style>